package com.huaxin.hxcloud.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.emmp_ard.scancapture.ScanCaptureActivity;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.StationDTO;
import com.huaxin.common.media.view.PhotoAddView;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.utils.Util;
import com.huaxin.common.view.BottomSheetDialog;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.CommonSearchActivity;
import com.huaxin.hxcloud.find.view.adapter.ImagePickerAdapter;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by Administrator on 2016/9/7.
 */
public class ReportFragment extends BaseFragment implements ImagePickerAdapter.OnRecyclerViewItemClickListener, ImagePickerAdapter.OnDeleteItemClickListener {


    @BindView(R.id.more)
    TextView     more;
    @BindView(R.id.toolbar)
    Toolbar      toolbar;
    @BindView(R.id.add_device)
    TextView     addDevice;
    @BindView(R.id.addDeviceLayout)
    LinearLayout addDeviceLayout;
    @BindView(R.id.fail_type)
    TextView     failType;
    @BindView(R.id.failTypeLayout)
    LinearLayout failTypeLayout;
    @BindView(R.id.desEdit)
    EditText     desEdit;
    @BindView(R.id.photo_add_view)
    PhotoAddView photoAddView;


    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    private int        currentfailType;
    private String     stationCode;
    private String     stationName;
    private StationDTO station;


    //选中数量限制
    private int maxImgCount = 4;
    private ArrayList<ImageItem> mSelImageList;
    public static final int IMAGE_ITEM_ADD       = -1;
    public static final int REQUEST_CODE_SELECT  = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private ImagePickerAdapter mImagePickerAdapter;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_report;
    }

    @Override
    protected void initView(View view) {
        more.setText("提交");
        toolbar.setTitle("故障申报");
        photoAddView.setMaxSize(8);

        ImagePicker picker = BaseApp.getImagePicker();
        if (picker != null) {
            picker.setSelectLimit(maxImgCount);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        mSelImageList = new ArrayList<>();
        mImagePickerAdapter = new ImagePickerAdapter(getContext(), mSelImageList, maxImgCount);
        mImagePickerAdapter.setOnItemClickListener(this);
        mImagePickerAdapter.setDeleteItemClickListener(this);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mImagePickerAdapter);
    }

    @Override
    protected void onResumeView() {
        super.onResumeView();
        ((BaseActivity) getActivity()).setSupportActionBar(toolbar);
    }

    @OnClick({R.id.more, R.id.addDeviceLayout, R.id.failTypeLayout})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.more:
                ApiAddSiteFeedback();
                break;
            case R.id.addDeviceLayout:
                hideIme();
                final String[] array = {"搜索站点", "扫描二维码"};
                BottomSheetDialog dialog = new BottomSheetDialog(getContext(), array, new
                        BottomSheetDialog.OnItemClickListener() {

                            @Override
                            public void onItemClick(int position) {
                                if (position == 0) {
                                    CommonSearchActivity.start(ReportFragment.this, CommonSearchActivity
                                            .MODE_SEARCH_STATION);
                                } else {
                                    ScanCaptureActivity.start(ReportFragment.this,
                                            ScanCaptureActivity.TYPE_QR_CODE, ScanCaptureActivity
                                                    .MODE_BIND_STATION);
                                }
                            }
                        });
                dialog.show();

                break;
            case R.id.failTypeLayout:
                hideIme();
                final String[] typeArray = {"厂站停电", "设备故障", "其他"};
                BottomSheetDialog typeDialog = new BottomSheetDialog(getContext(), typeArray, new
                        BottomSheetDialog.OnItemClickListener() {

                            @Override
                            public void onItemClick(int position) {
                                failType.setText(typeArray[position]);
                                currentfailType = position;
                            }
                        });
                typeDialog.show();

                break;
            default:
                break;

        }
    }

    private void ApiAddSiteFeedback() {
        String des = desEdit.getText().toString().trim();
        if (stationCode == null) {
            ToastUtil.showToast("请先选择站点！");
            return;
        }
        if (Util.checkNull(des)) {
            ToastUtil.showToast("描述不能为空！");
            return;
        }
        List<String> imageDatas = new ArrayList<>();
        for (int i = 0; i < mSelImageList.size(); i++) {
            String path = mSelImageList.get(i).path;
            imageDatas.add(path);
        }

        final Dialog dialog = DialogUtil.getWaitDialog(getContext(), "提交中...");
        dialog.show();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().addSiteFeedback(stationCode, currentfailType, des,
                RequestHelper.createFileParts(imageDatas.toArray(new String[imageDatas.size()])));
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                dialog.dismiss();
                if (response.isSuccessful() && baseDTO.getState() > 0) {
                    if (baseDTO != null && baseDTO.isSuccessful()) {
                        ToastUtil.showToast("提交成功");

                        getActivity().finish();
                    } else {
                        ToastUtil.showToast("提交失败");
                    }
                } else {
                    ToastUtil.showToast("提交失败");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast("网络故障");
            }
        });
    }


    private void hideIme() {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context
                .INPUT_METHOD_SERVICE);
        if (imm != null && imm.isActive(desEdit)) {
            imm.hideSoftInputFromWindow(desEdit.getWindowToken(), 0);
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Constants.RET_SEARCH
                    || requestCode == Constants.RET_SWEEP)
                if (data.hasExtra(Constants.IK_STATION_CODE)) {
                    stationCode = data.getStringExtra(Constants.IK_STATION_CODE);
                    if (data.hasExtra(Constants.IK_STATION_NAME)) {
                        stationName = data.getStringExtra(Constants.IK_STATION_NAME);
                        addDevice.setText(stationName);
                    }
                }

        } else if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    mSelImageList.addAll(images);
                    mImagePickerAdapter.setImages(mSelImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    mSelImageList.clear();
                    mSelImageList.addAll(images);
                    mImagePickerAdapter.setImages(mSelImageList);
                }
            }
        }
    }

    @Override
    public void onDeleteItemClick(int position) {
        if (mSelImageList.size() > 0) {
            mSelImageList.remove(position);
            mImagePickerAdapter.setImages(mSelImageList);
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - mSelImageList.size());
                Intent intent1 = new Intent(getContext(), ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
                //                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(getContext(), ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) mImagePickerAdapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }


}


